package com.pikaqiu.warehouse.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * 文件上传工具类
 */
@Slf4j
public class FileUtils extends FileUtil {

    public static String upload(String path, MultipartFile file) {
        String fileName = "";
        try {
            fileName = extractFilename(file);
            String absPath = getAbsoluteFile(path, fileName).getAbsolutePath();
            file.transferTo(Paths.get(absPath));
        } catch (IOException e) {
            log.error("文件上传失败", e);
        }
        return fileName;
    }

    public static File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile file) {
        return StringUtils.format("{}.{}",
                DateUtils.format(DateUtils.date(), DatePattern.PURE_DATETIME_PATTERN),
                getExtension(file));
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file) {
        return FileNameUtil.extName(file.getOriginalFilename());
    }

    public static boolean isExcel(String extension) {
        return StringUtils.equalsAnyIgnoreCase(extension, "xls", "xlsx", "csv");
    }
}
